package com.ssyc.gsk_teacher_appraisal.fragment;

import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.manager.MediaPlayerManager;
import com.ssyc.common.utils.SPUtil;
import com.ssyc.common.view.MyListView;
import com.ssyc.gsk_teacher_appraisal.R;
import com.ssyc.gsk_teacher_appraisal.activity.TkTeacherAppraisalQuestionActivity;
import com.ssyc.gsk_teacher_appraisal.adapter.ReadChooseAnswerAdapter;
import com.ssyc.gsk_teacher_appraisal.adapter.ReadShowAnswerAdapter;
import com.ssyc.gsk_teacher_appraisal.base.BaseLazyFragment;
import com.ssyc.gsk_teacher_appraisal.bean.AnswerInfo;
import com.ssyc.gsk_teacher_appraisal.bean.QuestionDetailsInfo;
import com.ssyc.gsk_teacher_appraisal.bean.ReadLvInfo;
import com.ssyc.gsk_teacher_appraisal.constant.TeacherAppKeys;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * 测评--听力单题单选
 * Created by Administrator on 2018/10/24 0024.
 */

public class AppraisalLinstenSingleChooseFragment extends BaseLazyFragment implements View.OnClickListener {

    //服务器返回的页面数据对象
    private QuestionDetailsInfo info;

    //构建的页面的数据模型,对于单体单选题型该AnswerInfo对象可以直接通过服务器返回的该题的数据模型进行组装
    private AnswerInfo answerInfo;


    //题目类型
    private TextView tvTitleType;

    //播放音频的按钮
    private ImageView ivPlay;

    //播放段落音频文件的帧动画对象
    private AnimationDrawable animationDrawable;

    //顶部布局
    private LinearLayout llTop;

    //底部布局
    private LinearLayout llBottom;

    //顶部的标题部分
    private TextView tvContent;

    //题干
    private TextView tvQuestion;

    //展示提供答题选项的列表
    private MyListView lv;

    //作答,学生成绩时显示
    private LinearLayout llZd;
    private TextView tvOwnAnswer;

    //1老师查看全校成绩 2老师预览试卷 3老师查看某个学生的成绩和学生查看自己的成绩  4学生答题
    private int autherType = -1;

    //正确答案,老师查看全校试卷1,老师预览2,学生查看自己成绩3  显示
    private TextView tvRightAnswer;
    private LinearLayout llZqda;

    //全校正确率,只有老师查看全校试卷1 显示
    private LinearLayout llQxzql;
    private TextView tvQxzql;

    //展示各个选项的正确率,只有老师查看全校试卷1 显示
    private MyListView lvShowAnswer;

    //解析
    private TextView tvParseAnswer;
    private LinearLayout llShowAnswer;


    //播放音频的Url地址,对于单体单选题直接从服务器返回的Url中取
    private String audioUrl = "";

    //答案选项的列表数据
    private List<ReadLvInfo> oldDatas;

    //答案选项的适配器
    private ReadChooseAnswerAdapter answerAdapter;

    //选项的字符数组
    private String[] letters = {"A", "B", "C", "D", "E", "F"};

    /**
     * 获取当前Framgent
     *
     * @return
     */
    public static final AppraisalLinstenSingleChooseFragment newInstance(QuestionDetailsInfo info) {
        AppraisalLinstenSingleChooseFragment appraisalLinstenSingleChooseFragment = new AppraisalLinstenSingleChooseFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("data", info);
        appraisalLinstenSingleChooseFragment.setArguments(bundle);
        return appraisalLinstenSingleChooseFragment;
    }


    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {

        //初始化视图
        initView(view);

        //获取传递的数据
        initIntent();

        //同步界面视图的显示与隐藏状态
        sycViewState();

        //设置选项答案列表
        initQuestionLv();

        //设置底部数据的方法
        initBottomData();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_teacher_class_listen_single_choose;
    }

    /**
     * 获取传递的数据
     */
    private void initIntent() {
        autherType = SPUtil.getInt(getContext(), TeacherAppKeys.AUTHERTYPE);

        //获取服务器返回的页面对象
        info = (QuestionDetailsInfo) getArguments().getSerializable("data");

        if (null == info) {
            return;
        }

        //获取题目类型
        String quetionTitle = info.getTitle_type();
        tvTitleType.setText(quetionTitle);

        //获取播放音频地址 这里需要拼接前缀
        audioUrl = info.getPath() + info.getContent();

        Log.i("test", "PATH:" + audioUrl);

        //组装页面数据模型
        answerInfo = new AnswerInfo();


        //获取小题的集合
        List<QuestionDetailsInfo.SubListBean> sub_list = info.getSub_list();

        //获取单选题的小题数据,单选题只有1个题目,所以取0
        if (null != sub_list && sub_list.size() != 0) {
            //单选题获取第0个元素
            QuestionDetailsInfo.SubListBean subListBean = sub_list.get(0);

            //题目的标题内容
            answerInfo.qustionContent = "";

            //用户选择的答案
            String chooseAnserByuser = "";
            if (TextUtils.isEmpty(subListBean.getStudent_option())) {
                chooseAnserByuser = "";
            } else {
                chooseAnserByuser = subListBean.getStudent_option();
            }
            answerInfo.chooseAnswer = chooseAnserByuser;

            //该题的正确答案
            String rightAnserQuestion = subListBean.getOption();
            answerInfo.rightAnswer = rightAnserQuestion;

            //全校的正确率
            answerInfo.proba = subListBean.getYes_pro();

            //解析
            answerInfo.explain = info.getAnalysis();

            //创建展示选项的数据集合
            List<ReadLvInfo> readLvInfos = new ArrayList<>();

            if (null != sub_list && sub_list.size() != 0) {
                //获取服务器返回的选项集合
                List<String> answerList = subListBean.getList();
                for (int i = 0; i < answerList.size(); i++) {
                    ReadLvInfo info = new ReadLvInfo();
                    //选项的编号
                    info.questionIndex = letters[i];
                    //用户选择的该题的答案,老师端进入时需要赋初值,学生端默认进入为空
                    info.chooseAnswer = chooseAnserByuser;
                    //该题的正确答案
                    info.rightAnswer = rightAnserQuestion;

                    //选项的选择率
                    //获取选项选择率的对象
                    QuestionDetailsInfo.SubListBean.ProBean pro = subListBean.getPro();
                    if (null != pro) {
                        if (i == 0) {
                            //选项A
                            if (TextUtils.isEmpty(pro.getA())) {
                                info.probability = "0.0%";
                            } else {
                                info.probability = pro.getA();
                            }
                        } else if (i == 1) {
                            //选项B
                            if (TextUtils.isEmpty(pro.getB())) {
                                info.probability = "0.0%";
                            } else {
                                info.probability = pro.getB();
                            }
                        } else if (i == 2) {
                            //选项C
                            if (TextUtils.isEmpty(pro.getC())) {
                                info.probability = "0.0%";
                            } else {
                                info.probability = pro.getC();
                            }
                        } else if (i == 3) {
                            //选项D
                            if (TextUtils.isEmpty(pro.getD())) {
                                info.probability = "0.0%";
                            } else {
                                info.probability = pro.getD();
                            }
                        } else if (i == 4) {
                            //选项E
                            if (TextUtils.isEmpty(pro.getE())) {
                                info.probability = "0.0%";
                            } else {
                                info.probability = pro.getE();
                            }
                        } else if (i == 5) {
                            //选项F
                            if (TextUtils.isEmpty(pro.getF())) {
                                info.probability = "0.0%";
                            } else {
                                info.probability = pro.getF();
                            }
                        }
                    }


                    //选项的具体内容
                    info.questionContent = answerList.get(i);
                    readLvInfos.add(info);
                }
            }
            answerInfo.readLvInfos = readLvInfos;
            oldDatas = answerInfo.readLvInfos;
        }
    }


    /**
     * 初始化视图的方法
     */
    private void initView(View view) {
        tvTitleType = view.findViewById(R.id.tv_title_type);
        ivPlay = view.findViewById(R.id.iv_play);
        ivPlay.setOnClickListener(this);
        llTop = view.findViewById(R.id.ll_top);
        llBottom = view.findViewById(R.id.ll_bottom);
        tvContent = view.findViewById(R.id.tv_content);
        tvQuestion = view.findViewById(R.id.tv_question);
        lv = view.findViewById(R.id.lv);
        tvOwnAnswer = view.findViewById(R.id.tv_own_answer);
        llZd = view.findViewById(R.id.ll_zd);
        tvRightAnswer = view.findViewById(R.id.tv_right_answer);
        llZqda = view.findViewById(R.id.ll_zqda);
        tvQxzql = view.findViewById(R.id.tv_qxzql);
        llQxzql = view.findViewById(R.id.ll_qxzql);
        lvShowAnswer = view.findViewById(R.id.lv_show_answer);
        tvParseAnswer = view.findViewById(R.id.tv_parse_answer);
        llShowAnswer = view.findViewById(R.id.ll_show_answer);
        llTop.setVisibility(View.VISIBLE);
        llBottom.setVisibility(View.VISIBLE);
    }

    /**
     * 根据教师端和学生端不同入口状态
     * 同步界面视图的显示与隐藏方法
     */
    private void sycViewState() {

        //1老师查看全校成绩 2老师预览试卷 3老师查看某个学生的成绩和学生查看自己的成绩  4学生答题
        if (autherType == 1) {
            //老师查看全校成绩
            //作答不显示
            llZd.setVisibility(View.GONE);

        } else if (autherType == 2) {
            //老师预览试卷
            //作答不显示
            llZd.setVisibility(View.GONE);
            //全校正确率不显示
            llQxzql.setVisibility(View.GONE);
            //选项正确率的列表不显示
            lvShowAnswer.setVisibility(View.GONE);

        } else if (autherType == 3) {
            //老师查看学生成绩和学生查看自己的成绩
            //全校正确率不显示
            llQxzql.setVisibility(View.GONE);
            //选项正确率的列表不显示
            lvShowAnswer.setVisibility(View.GONE);

        } else if (autherType == 4) {
            //学生进入答题
            llShowAnswer.setVisibility(View.GONE);
        }
    }


    /**
     * 音频播放,帧动画播放的方法
     */
    private void doPlayVoiceAnim(String voiceUrl) {
        if (!TextUtils.isEmpty(voiceUrl)) {

            if (null != animationDrawable && animationDrawable.isRunning()) {
                stopVoiceAnim();
            }

            //进行帧动画操作
            animationDrawable = (AnimationDrawable) ivPlay.getBackground();
            if (null == animationDrawable) {
                return;
            }
            animationDrawable.start();
            //播放音频
            MediaPlayerManager.getInstance().play(voiceUrl, new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    if (null != animationDrawable) {
                        stopVoiceAnim();
                    }
                }
            }, new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                    if (null != animationDrawable) {
                        stopVoiceAnim();
                    }
                    return false;
                }
            });
        }
    }


    /**
     * 停止帧动画播放,还原按钮状态的方法
     */
    private void stopVoiceAnim() {
        animationDrawable.stop();
        animationDrawable = null;
        ivPlay.setBackgroundResource(R.drawable.teacher_class_voice_big_anim);
        MediaPlayerManager.getInstance().stop();
    }


    /**
     * 设置答案选项列表ListView的方法
     */
    private void initQuestionLv() {

        if (autherType == 1 || autherType == 2) {
            //老师端查看全国试卷和老师预览,不需要展示学生选择的答案
            answerAdapter = new ReadChooseAnswerAdapter(1, 0, getContext(), oldDatas, R.layout.teacher_class_lv_read_choose_answer);
        } else if (autherType == 3) {
            //老师端查看学生成绩,需要展示学生选择的答案
            answerAdapter = new ReadChooseAnswerAdapter(1, 1, getContext(), oldDatas, R.layout.teacher_class_lv_read_choose_answer);
        } else if (autherType == 4) {
            //学生端答题
            answerAdapter = new ReadChooseAnswerAdapter(0, getContext(), oldDatas, R.layout.teacher_class_lv_read_choose_answer);
            //设置条目点击事件
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
                    if (oldDatas.get(pos).isSelected) {
                        return;
                    } else {
                        //同步数据状态
                        answerAdapter.upDateStete(pos);
                        //保存选择的答案
                        //通过EventBs将用户作答本小题的相关信息传递给TkMainActivity保存
                        //currPos对应的每个大题的小题的位置,单选题默认就一个小题
                        int choosePos = 0;
                        //是否如正确
                        boolean chooseResult = false;
                        if (oldDatas.get(pos).rightAnswer.equals(oldDatas.get(pos).questionContent)) {
                            //用户作答正确
                            chooseResult = true;
                        } else {
                            //用户作答错误
                            chooseResult = false;
                        }
                        BusInfo busInfo = new BusInfo();
                        busInfo.tkMsg = TeacherAppKeys.TKMsg;
                        busInfo.tkChoosePos = choosePos;
                        busInfo.tkChooseAnswer = oldDatas.get(pos).questionIndex;
                        busInfo.tkChooseResult = chooseResult;
                        EventBus.getDefault().post(busInfo);
                    }
                }
            });
        }
        lv.setAdapter(answerAdapter);
    }


    /**
     * 设置底部数据的方法
     */
    private void initBottomData() {

        if (llShowAnswer.getVisibility() == View.VISIBLE) {
            //非学生端进入时需要显示底部数据

            if (lvShowAnswer.getVisibility() == View.VISIBLE) {
                //正确率需要显示时才设置选项正确率的列表
                ReadShowAnswerAdapter answerAdapter = new ReadShowAnswerAdapter(getContext(), oldDatas, R.layout.teacher_class_lv_read_show_answer);
                lvShowAnswer.setAdapter(answerAdapter);
            }

            //设置作答
            if (llZd.getVisibility() == View.VISIBLE) {
                //作答需要显示时才设置作答内容
                if (TextUtils.isEmpty(answerInfo.chooseAnswer)) {
                    tvOwnAnswer.setVisibility(View.INVISIBLE);
                } else {
                    tvOwnAnswer.setVisibility(View.VISIBLE);
                    tvOwnAnswer.setText(answerInfo.chooseAnswer);
                    if (answerInfo.chooseAnswer.equals(answerInfo.rightAnswer)) {
                        tvOwnAnswer.setBackgroundResource(R.drawable.teacher_class_tv_right_answer);
                    } else {
                        tvOwnAnswer.setBackgroundResource(R.drawable.teacher_class_tv_own_choose_answer);
                    }
                }


            }

            //正确答案
            tvRightAnswer.setText(answerInfo.rightAnswer);

            //设置解析
            tvParseAnswer.setText(answerInfo.explain);

            //设置全校正确率
            if (llQxzql.getVisibility() == View.VISIBLE) {
                //全校争取率需要显示时才设置
                tvQxzql.setText(answerInfo.proba);
            }

        }
    }


    /**
     * 事件处理
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (null != busInfo && TkTeacherAppraisalQuestionActivity.VPSCOLL.equals(busInfo.vpScoll)) {
            //Vp的滚动监听事件,如果是正在播放音频状态,停止播放,同时还原按钮状态
            if (null != animationDrawable && animationDrawable.isRunning()) {
                stopVoiceAnim();
            }
        }
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_play) {
            //播放音频
            doPlayVoiceAnim(audioUrl);
        }
    }

    @Override
    public void onDestroy() {
        //停止帧动画
        if (null != animationDrawable && animationDrawable.isRunning()) {
            stopVoiceAnim();
        }
        super.onDestroy();
    }
}
